package com.terrace.controller.system;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.terrace.core.common.model.ResultData;
import com.terrace.db.system.mapper.entity.Role;
import com.terrace.db.system.mapper.entity.User;
import com.terrace.db.system.mapper.entity.UserRole;
import com.terrace.db.system.service.RoleService;
import com.terrace.db.system.service.UserService;
import com.terrace.core.mybatis.entity.Pagination;
import com.terrace.core.utils.ApplicationContextUtil;
import com.terrace.core.utils.UUIDGenerator;
import com.terrace.web.annotation.Logs;
import com.terrace.web.constant.GlobalsConstant;
import com.terrace.web.model.DataGrid;

/**
 * 角色管理
 * @author jiangyg
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/role")
public class RoleController {
	
	private static final String MESSAGE_TYPE = "角色";
	
	@Autowired
	private RoleService roleService;
	
	/**
	 * 默认管理页面
	 * @param request
	 * @return
	 */
	@RequestMapping
	public ModelAndView roleList(HttpServletRequest request){
		return new ModelAndView("system/role/roleList");
	}
	
	/**
	 * 角色下的用户列表页面
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "userList")
	public ModelAndView userList(@RequestParam("roleId") String roleId, HttpServletRequest request){
		request.setAttribute("roleId", roleId);
		return new ModelAndView("system/role/userList");
	}
	
	/**
	 * 跳转至还未授予该角色的用户列表界面
	 * @param roleId
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "userAuth")
	public ModelAndView userAuth(@RequestParam("roleId") String roleId, HttpServletRequest request){
		request.setAttribute("roleId", roleId);
		return new ModelAndView("system/role/userAuth");
	}
	
	/**
	 * 设置权限页面
	 * @param roleId
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "setPermission")
	public ModelAndView setPermission(@RequestParam(value = "roleId") String roleId, HttpServletRequest request){
		request.setAttribute("roleId", roleId);
		return new ModelAndView("system/role/setPermission");
	}
	
	/**
	 * 数据表格
	 * @param request
	 * @param pagination
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "datagrid")
	@RequiresPermissions("system:role:view")
	public DataGrid<Role> datagrid(Role role, Pagination<Role> pagination, HttpServletRequest request) {
		DataGrid<Role> dataGrid = new DataGrid<Role>();
		dataGrid.setPagination(roleService.selectRolesBySelective(role, pagination));
		return dataGrid;
	}
	
	/**
	 * 新增或者修改页面
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(String id, HttpServletRequest request){
		if (StringUtils.isNotBlank(id)) {
			Role role = roleService.selectByRoleId(id);
			request.setAttribute("role", role);
		}
		return new ModelAndView("system/role/role");
	}
	
	/**
	 * 保存角色
	 * @param role
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequestMapping(params = "saveOrUpdate")
	@RequiresPermissions("system:role:save")
	@Logs(depict = "保存角色", type = GlobalsConstant.LogTypes.SYS_ROLE)
	public ResultData saveOrUpdate(Role role, HttpServletRequest request) {
		ResultData rd = new ResultData();
		if (StringUtils.isBlank(role.getId())) {
			role.setId(UUIDGenerator.generate());
			roleService.saveRoleSelective(role);
			rd.successObjs("10001", MESSAGE_TYPE);
		} else {
			Role temp = roleService.selectByRoleId(role.getId());
			if (temp == null) {
				return rd.failObjs("13103", MESSAGE_TYPE);
			}
			roleService.updateByRoleIdSelective(role);
			rd.successObjs("10002", MESSAGE_TYPE);
		}
		return rd;
	}
	
	/**
	 * 角色授予用户
	 * @param role
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequestMapping(params = "roleGrantUser")
	@RequiresPermissions("system:role:grant:user")
	@Logs(depict = "角色授予用户", type = GlobalsConstant.LogTypes.SYS_ROLE)
	public ResultData roleGrantUser(@RequestParam("userId") String userId, 
			@RequestParam("roleId") String roleId, HttpServletRequest request) {
		ResultData rd = new ResultData();
		UserService userService = ApplicationContextUtil.getContext().getBean(UserService.class);
		Role role = roleService.selectByRoleId(roleId);
		User user = userService.selectUserById(userId);
		if (user == null || role == null) {
			return rd.failObjs("13105");
		}
		UserRole userRole = new UserRole();
		userRole.setId(UUIDGenerator.generate());
		userRole.setRole(role);
		userRole.setUser(user);
		roleService.roleGrantUser(userRole);
		return rd.success("用户[" + user.getUserAccount() + "]授予角色[" + role.getRoleName() + "]成功。");
	}
	
	/**
	 * 删除用户授权
	 * @param userId
	 * @param roleId
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequestMapping(params = "deleteAccredit")
	@RequiresPermissions("system:role:delete:accredit")
	@Logs(depict = "删除用户授权", type = GlobalsConstant.LogTypes.SYS_ROLE)
	public ResultData deleteAccredit(@RequestParam("userId") String userId, 
			@RequestParam("roleId") String roleId, HttpServletRequest request) {
		ResultData rd = new ResultData();
		UserService userService = ApplicationContextUtil.getContext().getBean(UserService.class);
		Role role = roleService.selectByRoleId(roleId);
		User user = userService.selectUserById(userId);
		if (user == null || role == null) {
			return rd.failObjs("13105");
		}
		roleService.deleteByUserAndRoleId(userId, roleId);
		return rd.success("删除用户[" + user.getUserAccount() + "]角色[" + role.getRoleName() + "]成功。");
	}
	
	/**
	 * 删除角色
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "delete")
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequiresPermissions("system:role:delete")
	@Logs(depict = "删除角色", type = GlobalsConstant.LogTypes.SYS_ROLE)
	public ResultData delete(@RequestParam(value = "id") String roleId, HttpServletRequest request) {
		ResultData rd = new ResultData();
		Role role = roleService.selectByRoleId(roleId);
		if (role == null) {
			return rd.failObjs("13103", MESSAGE_TYPE);
		}
		
		// 角色中是否存在
		UserService userService = ApplicationContextUtil.getContext().getBean(UserService.class);
		Pagination<User> pagination = new Pagination<User>();
		Role queryRole = new Role();
		queryRole.setId(roleId);
		userService.selectUsersInRoleForPagination(pagination, new User(), queryRole);
		if (pagination.getTotal() > 0) {
			return rd.fail("角色[" + role.getRoleName() + "]已存在用户，要想删除该角色请先删除其下的用户！");
		}
		
		int result = roleService.deleteRoleById(roleId);
		if (result != 1) {
			rd.failObjs("13102", MESSAGE_TYPE);
		} else {
			rd.successObjs("10003", MESSAGE_TYPE);
		}
		return rd;
	}

}
